#include "game_time.h"
#include "game_log.h"
#include <assert.h>
#include <unistd.h>

void __log(const char * format, ...){
  va_list args;
  va_start(args,format);

  vfprintf(stdout,format,args);
  vfprintf(stdout,"\n",nullptr);

  va_end(args);
}

void print_tm(const char *title, tm *tm)
{
    __log("%s: %d-%d-%d %d:%d:%d", title, tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
}

void print_cur_utc_time(const char *title)
{
    char timeStr[128];
    time_t cur_utc = __get_sys_time_utc();
    tm cur_utc_tm = __get_sys_time_utc_tm();
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &cur_utc_tm);
    __log("%s: [UTC]%d [UTC]%s", title, (long)cur_utc, timeStr);
}
void print_cur_local_time(const char *title)
{
    char timeStr[128];
    time_t cur_local = __get_sys_time_local();
    tm cur_local_tm = __get_sys_time_local_tm();
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &cur_local_tm);
    __log("%s: [LOCAL]%d [LOCAL]%s", title, (long)cur_local, timeStr);
}

void wait(int sec)
{
    __log("等待%d秒", sec);
    ::sleep(sec);
}

int main()
{
    time_t cur_utc;
    tm cur_utc_tm;

    __log("UTC测试------------------------");
    time_t old_utc = __get_sys_time_utc();
    tm old_utc_tm = __get_sys_time_utc_tm();
    __log("测试前time_t: %ld", (long)old_utc);
    print_cur_utc_time("测试前时间");

    wait(3);
    print_cur_utc_time("等待后时间");

    // 用time_t还原
    __set_sys_time_utc(old_utc);
    print_cur_utc_time("time_t还原后时间");
    assert(old_utc == __get_sys_time_utc());

    wait(3);
    print_cur_utc_time("等待后时间");

    // 用tm还原
    __set_sys_time_utc_tm(&old_utc_tm);
    print_cur_utc_time("tm还原后时间");
    assert(old_utc == __get_sys_time_utc());
    __log("utc done");
    wait(3);


    __log("本地时间测试------------------------");
    time_t old_local = __get_sys_time_local();
    tm old_local_tm = __get_sys_time_local_tm();
    print_cur_local_time("测试前时间");

    wait(3);
    print_cur_local_time("等待后时间");

    // time_t还原时间
    assert(__set_sys_time_local(old_local));
    print_cur_local_time("time_t还原后时间");
    assert(old_local == __get_sys_time_local());

    wait(3);
    print_cur_local_time("等待后时间");

    // 用tm结构还原
    assert(__set_sys_time_local_tm(&old_local_tm));
    assert(old_local == __get_sys_time_local());
    print_cur_local_time("tm还原后时间");
    __log("local done");

    return 0;
}
